package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.dto.CategoryPageDTO;
import com.example.entity.Category;
import com.example.entity.Article;
import com.example.mapper.CategoryMapper;
import com.example.mapper.ArticleMapper;
import com.example.service.CategoryService;
import com.example.vo.CategoryListVO;
import com.example.vo.CategoryVO;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 分类表 服务实现类
 * </p>
 *
 * @author wuyunbin
 * @since 2024-10-15
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Resource
    private CategoryMapper categoryMapper;

    @Resource
    private ArticleMapper articleMapper;

    @Override
    public List<CategoryListVO> getSelectList() {
        List<Category> categories = this.list();
        List<CategoryListVO> voList = new ArrayList<>();
        for (Category category : categories) {
            CategoryListVO vo = new CategoryListVO();
            vo.setLabel(category.getName());
            vo.setValue(category.getId());
            voList.add(vo);
        }
        return voList;
    }

    @Override
    public IPage<Category> getPage(CategoryPageDTO categoryPageDTO) {
        // 创建分页对象
        Page<Category> page = new Page<>(categoryPageDTO.getCurrent(), categoryPageDTO.getSize());
        
        // 创建查询条件
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(categoryPageDTO.getCategoryName() != null, Category::getName, categoryPageDTO.getCategoryName())
               .between(categoryPageDTO.getStartDate() != null, Category::getCreateTime, 
                       categoryPageDTO.getStartDate(), categoryPageDTO.getEndDate())
               .orderByDesc(Category::getCreateTime);
        
        // 执行分页查询
        return this.page(page, wrapper);
    }

    @Override
    public List<CategoryVO> getCategoryList() {
        // 从数据库获取所有分类
        List<Category> categories = this.list();
        // 转换为前端需要的格式
        List<CategoryVO> voList = new ArrayList<>();
        for (Category category : categories) {
            CategoryVO vo = new CategoryVO();
            vo.setId(category.getId());
            vo.setName(category.getName());
            // 获取分类下的文章数量
            LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Article::getCategoryId, category.getId());
            Long countLong = articleMapper.selectCount(wrapper);
            vo.setArticleCount(countLong.intValue());
            voList.add(vo);
        }
        return voList;
    }
}
